import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';
@Component({
  selector: 'app-commentlist',
  templateUrl: './commentlist.component.html',
  styleUrls: ['./commentlist.component.scss']
})
export class CommentlistComponent {
  MusicCommentList: any[] = []
  /**
   * @type {string} searchText
   * 搜索方法绑定的搜索查询字符
   */
  searchText: string = ""
  /**
  * @type {boolean} showDelete
  * 控制垃圾箱的两种状态
  */
  showDelete: boolean = false
  /**
   * @type {number} deleteCount
   * 记录删除的数量 初始值 0
   */
  deleteCount: number = 0
  /**
  * @type {string} albumId 
  * 获取歌单的id的变量
  */
  albumId: string = ''
  /**
   * 
   * @param router 导入路由Router
   * @param route 导入路由ActivatedRoute
   */
  constructor(private router: Router, private route: ActivatedRoute) {
    this.route.queryParamMap.subscribe((data) => {
      this.albumId = ((data as any).params.id)
      this.refresh();
    })
  }

  //搜索API
  search(ev?: Event) {
    if (ev) {
      if ((ev as any).code != 'Enter') return
    }
    //  $regex  正则表达式  模糊匹配
    /**
    * @property {string} searchParams
    * 定义搜索字段的参数，在getMusicCommentList()方法里调用
    */
    let searchParams = `,"content":{"$regex":"${this.searchText}"}`
    console.log(searchParams)
    this.getMusicCommentList(searchParams)
  }
  /**
   * @property {function} refresh
   * 刷新方法
   */
  refresh() {
    this.getMusicCommentList();
    this.getDeleteCount();
  }

  /**
   * @property {function} addNewMusic
   * 添加评论 跳转到对应的编辑页里
   */
  addNewMusicComment() {
    this.router.navigate(["/music/comment/edit"], {
      queryParams: {
        new: true
      }
    })
  }
/**
   * @property {function} onShowDelete
   * 改变垃圾箱的状态
   * @param {boolean} showDelete 
   * 根据 !this.showDelete的状态
   */
  onShowDelete() {
    this.showDelete = !this.showDelete
    this.refresh()
  }
  /**
   * 获取删除的数量的方法
   * @return {Promise<number>}
   */
  async getDeleteCount() {
    let url = `http://metapunk.cn:9999/parse/classes/MusicComment?where={"isDeleted":true}&count=1&limit=0`

    let result = await fetch(url, {
      "headers": {
        "x-parse-application-id": "dev"
      },
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });
    let data = await result.json();
    console.log(data)
    this.deleteCount = data.count || 0
  }


  /**
   * 获取 评论歌单信息
   * @param {string} searchParams  搜索字段
   * @returns 获得数据结果的json对象
   */
  async getMusicCommentList(searchParams = '') {
    let url = "http://metapunk.cn:9999/parse/classes/MusicComment?"
    // 排序
    let paramsOrder = `order=-createdAt`
    url += paramsOrder
    //  获取歌单的ID
    let paramsId = ""
    if (!this.albumId) {
    } else {
      paramsId = `,"album":"${this.albumId}"`
    }

    // 匹配
    let paramsWhere;
    if (!this.showDelete) {
      paramsWhere = `where={"isDeleted":false${searchParams}${paramsId}}`
      url += "&" + paramsWhere
    } else {
      paramsWhere = `where={"isDeleted":true${searchParams}${paramsId}}`
      url += "&" + paramsWhere
    }
    // include包含    指针真实数据条件
    let paramsInclude = "include=user,music,album";
    url += "&" + paramsInclude
    console.log(url)


    let result = await fetch(url, {
      "headers": {
        "x-parse-application-id": "dev"
      },
      "body": null,
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });
    let data = await result.json()
    console.log(data)
    this.MusicCommentList = data.results
    console.log(this.MusicCommentList)
  }
  /**
   * 删除评论歌单
   *  @property {function} deleteMusicComment 
   * @param id  对应评论歌单id的内容
   * @param isRestore  是否删除成功
   * @returns 
   */
  async deleteMusicComment(id: any, isRestore: boolean = false) {
    let isDeleted = true
    if (isRestore == true) {
      isDeleted = false
    }
    // 发送HTTP请求，将isDeleted字段更新为true;
    let objectId = id.objectId
    if (objectId) {
      let response = await fetch(`http://metapunk.cn:9999/parse/classes/MusicComment/${objectId}`, {
        "headers": {
          "content-type": "text/plain;charset=UTF-8",
          "x-parse-application-id": "dev"
        },
        "body": `{"isDeleted":${isDeleted}}`,
        "method": "PUT",
        "mode": "cors",
        "credentials": "omit"
      });
      let data = await response.json()
      console.log(data)
      if (data?.updatedAt) {
        // 内存变量删除该项
        let idx = this.MusicCommentList.findIndex(item => item.name == id.name)
        this.MusicCommentList.splice(idx, 1)
        if (isDeleted) {
          this.deleteCount++;
        } else {
          this.deleteCount--;
        }
      }
    }
    return
  }
  // 编辑
  editMusicComment(music: any) {
    console.log(music)
  }
}
